package com.tinyengine.it.security;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tinyengine.it.mapper.TUserMapper;
import com.tinyengine.it.model.entity.TUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final TUserMapper tUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询用户
        TUser user = tUserMapper.selectOne(new LambdaQueryWrapper<TUser>().eq(TUser::getUsername, username).last("limit 1"));

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 检查用户状态
        //if (user.getStatus() != 1) {
        //    throw new UsernameNotFoundException("用户已被禁用: " + username);
        //}

        // 转换为 Spring Security 的 UserDetails 对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                true,               // enabled
                true,               // accountNonExpired
                true,               // credentialsNonExpired
                true,               // accountNonLocked
                new ArrayList<>()   // 由于我们不需要角色，这里传空集合
        );
    }
}